package com.windowes.weichang.exception;

import com.windowes.weichang.common.ServerResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static javax.servlet.http.HttpServletResponse.*;
import static org.springframework.http.HttpStatus.*;

@RestController
public class ErrorHandler implements ErrorController {

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public ServerResponse error(HttpServletRequest request, HttpServletResponse response) {
        String message = "";
        String data = request.getPathInfo();
        switch (response.getStatus()) {
            case SC_NOT_FOUND:
                message = "未找到路由,请确认!";
                break;
            case SC_FORBIDDEN:
                message = "没有权限访问此站!";
                break;
            case SC_UNAUTHORIZED:
                message = "用户信息未获得授权!";
                break;
            case SC_METHOD_NOT_ALLOWED:
                message = "接口method不对,当前为:【" + request.getMethod() + "】!";
                break;
            case SC_INTERNAL_SERVER_ERROR:
            default:
                message = "服务器内部错误,请联系管理员!";
                break;
        }
        return ServerResponse.createByError(message, data);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}
